package com.lhq.plugin.handler.camel;

import org.apache.commons.lang3.StringUtils;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.TextSelection;
import org.eclipse.ui.texteditor.ITextEditor;

import com.lhq.plugin.handler.BaseHandler;

public class CamelHandler extends BaseHandler {
	
	@Override
    public Object execute(ExecutionEvent event) throws ExecutionException {
        ITextEditor ite = super.getTextEditor();
        TextSelection selection = super.getTextSelection(ite);
        IDocument document = super.getDocument(ite);
        String selectText = super.getSelectText(document, selection);

        this.handler(selectText, ite, selection, document);
		return null;
	}

    private void handler(String selected, ITextEditor ite, TextSelection selection, IDocument document) {
        if (StringUtils.isBlank(selected)) {
            return;
        }

		if (selected.indexOf('_') != -1) {
            selected = selected.toLowerCase();
			selected = selected.replaceAll("_([A-Z])", "$1");
			int i = -32;
			for (char c = 'a'; c <= 'z'; c = (char) (c + '\001'))
				selected = selected.replaceAll("_" + c, String.valueOf((char) (c + i)));
		} else {
			selected = selected.replaceAll("(?<![A-Z])([A-Z])", "_$1");
			selected = selected.toLowerCase();
			if (selected.charAt(0) == '_') {
				selected = selected.substring(1);
			}
		}

        try {
            document.replace(selection.getOffset(), selection.getLength(), selected);
            ite.selectAndReveal(selection.getOffset(), selected.length());
        } catch (Exception e) {

        }
	}
}